package co.legu.carpool.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 * POI 工具类
 */
public class POI {
    protected POI() {
        throw new UnsupportedOperationException();
    }

    /**
     * 从行中读取某个单元格的内容，并将其转换为字符串后返回
     * @param row 行
     * @param idx 行的索引(从 0 开始)
     * @return 读取到的内容
     */
    public static String readCellAsString(Row row, int idx) {
        Cell cell;
        try {
            cell = row.getCell(idx);
        } catch (RuntimeException e) {
            return "";
        }

        switch (cell.getCellType()) {
            case _NONE:
                return "";
            case NUMERIC:
                double num = cell.getNumericCellValue();
                if (
                        num <= 9007199254740991.0 && // 2 ** (52 + 1) - 1
                        num >= -(9007199254740991.0) && // -(2 ** (52 + 1) - 1)
                        (long) num == num
                ) {
                    return Long.toString((long) num);
                } else {
                    return Double.toString(num);
                }
            case STRING:
                return cell.getStringCellValue();
            case FORMULA:
                return cell.getStringCellValue();
            case BLANK:
                return "";
            case BOOLEAN:
                return Boolean.toString(cell.getBooleanCellValue());
            case ERROR:
                return "";
            default:
                throw new UnsupportedOperationException();
        }
    }
}
